package com.ocgs.base.util;

import com.ocgs.base.core.constant.BaseConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class EntitySort<T> implements Comparator<T> {
	private static final Log logger = LogFactory.getLog(EntitySort.class);
	private String sortFlg;
	private String sortKey;
	private List<T> list;

	public EntitySort(List<T> list, String sortKey, String sortFlg) {
		this.list = list;
		this.sortKey = sortKey;
		this.sortFlg = sortFlg;
	}

	public EntitySort(List<T> list, String sortKey) {
		this.list = list;
		this.sortKey = sortKey;
	}

	public List<T> sort() {
		Collections.sort(list, this);

		// sorted list
		return this.list;
	}

	@Override
	public int compare(T o1, T o2) {
		StringBuffer methodName = new StringBuffer();
		methodName.append("get");
		methodName.append(sortKey.substring(0, 1).toUpperCase());
		methodName.append(sortKey.substring(1));

		Object keyOne = null;
		Object keyTwo = null;
		try {
			keyOne = ((T) o1).getClass().getMethod(methodName.toString(), null)
					.invoke((T) o1, null);
			keyTwo = ((T) o2).getClass().getMethod(methodName.toString(), null)
					.invoke((T) o2, null);

			if (keyOne == null) {
				keyOne = "";
			}

			if (keyTwo == null) {
				keyTwo = "";
			}
		} catch (NoSuchMethodException ne) {
			logger.error(ne);
		} catch (IllegalAccessException ie) {
			logger.error(ie);
		} catch (InvocationTargetException it) {
			logger.error(it);
		}
		if (BaseConstants.SORT_FLAG_DESC.equals(sortFlg)) {
			return -(keyOne.toString().compareTo(keyTwo.toString()));
		} else {
			return keyOne.toString().compareTo(keyTwo.toString());
		}
	}

}
